<?php
session_start();
include('../includes/config.php');
include('../includes/functions.php');

// 检查用户是否已登录，且是医生角色
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'doctor') {
    header("Location: ../login.php");
    exit();
}

// 获取医生信息
$doctor_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users u JOIN doctors d ON u.id = d.user_id WHERE u.id = ?");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$doctor_info = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 处理状态更新请求
if (isset($_POST['update_status']) && isset($_POST['appointment_id']) && isset($_POST['status'])) {
    $appointment_id = $_POST['appointment_id'];
    $status = $_POST['status'];
    
    $stmt = $conn->prepare("UPDATE appointments SET status = ? WHERE id = ? AND doctor_id = ?");
    $stmt->bind_param("sii", $status, $appointment_id, $doctor_info['id']);
    
    if ($stmt->execute()) {
        $_SESSION['success_msg'] = "预约状态已成功更新！";
    } else {
        $_SESSION['error_msg'] = "更新预约状态时出错：" . $conn->error;
    }
    $stmt->close();
    
    // 重定向以防止重复提交
    header("Location: appointments.php");
    exit();
}

// 处理筛选参数
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$date_filter = isset($_GET['date']) ? $_GET['date'] : '';
$search_filter = isset($_GET['search']) ? $_GET['search'] : '';

// 构建查询
$sql = "SELECT a.*, p.name as patient_name, p.phone as patient_phone, d.name as doctor_name, dept.name as department_name 
        FROM appointments a 
        JOIN patients p ON a.patient_id = p.id 
        JOIN doctors d ON a.doctor_id = d.id 
        JOIN departments dept ON a.department_id = dept.id 
        WHERE a.doctor_id = ?";
$params = array($doctor_info['id']);
$types = "i";

// 添加筛选条件
if (!empty($status_filter)) {
    $sql .= " AND a.status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

if (!empty($date_filter)) {
    $sql .= " AND a.appointment_date = ?";
    $params[] = $date_filter;
    $types .= "s";
}

if (!empty($search_filter)) {
    $sql .= " AND (p.name LIKE ? OR p.phone LIKE ?)";
    $search_term = "%$search_filter%";
    $params[] = $search_term;
    $params[] = $search_term;
    $types .= "ss";
}

// 添加排序
$sql .= " ORDER BY a.appointment_date DESC, a.appointment_time DESC";

// 准备和执行查询
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$appointments = $stmt->get_result();
$stmt->close();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预约管理 - 医生工作站</title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
    <link rel="stylesheet" href="/assets\css/all_de197510.min.css">
    <link rel="stylesheet" href="/assets\css/flatpickr_01e5beab.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <img src="../assets/images/hospital-logo.png" alt="医院标志" class="img-fluid rounded-circle mx-auto d-block" style="width: 80px;">
                        <h5 class="text-white mt-2"><?php echo htmlspecialchars($doctor_info['name']); ?></h5>
                        <p class="text-muted"><?php echo htmlspecialchars($doctor_info['department_name']); ?></p>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="index.php">
                                <i class="fas fa-home"></i> 工作台首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active text-white" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> 预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="patients.php">
                                <i class="fas fa-user-injured"></i> 患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="records.php">
                                <i class="fas fa-notes-medical"></i> 病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="prescriptions.php">
                                <i class="fas fa-prescription"></i> 处方管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="schedule.php">
                                <i class="fas fa-clock"></i> 排班管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="profile.php">
                                <i class="fas fa-user-md"></i> 个人信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="../logout.php">
                                <i class="fas fa-sign-out-alt"></i> 退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">预约管理</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <a href="appointments.php" class="btn btn-sm btn-outline-secondary">全部预约</a>
                            <a href="appointments.php?status=pending" class="btn btn-sm btn-outline-warning">待确认</a>
                            <a href="appointments.php?status=confirmed" class="btn btn-sm btn-outline-primary">已确认</a>
                            <a href="appointments.php?date=<?php echo date('Y-m-d'); ?>" class="btn btn-sm btn-outline-info">今日预约</a>
                        </div>
                    </div>
                </div>

                <?php if (isset($_SESSION['success_msg'])): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php 
                        echo $_SESSION['success_msg']; 
                        unset($_SESSION['success_msg']);
                        ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['error_msg'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php 
                        echo $_SESSION['error_msg']; 
                        unset($_SESSION['error_msg']);
                        ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- 筛选表单 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form action="" method="GET" class="row g-3">
                            <div class="col-md-3">
                                <label for="status" class="form-label">状态</label>
                                <select name="status" id="status" class="form-select">
                                    <option value="">全部状态</option>
                                    <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>待确认</option>
                                    <option value="confirmed" <?php echo $status_filter == 'confirmed' ? 'selected' : ''; ?>>已确认</option>
                                    <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>已完成</option>
                                    <option value="cancelled" <?php echo $status_filter == 'cancelled' ? 'selected' : ''; ?>>已取消</option>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="date" class="form-label">日期</label>
                                <input type="date" class="form-control datepicker" id="date" name="date" value="<?php echo $date_filter; ?>">
                            </div>
                            <div class="col-md-4">
                                <label for="search" class="form-label">搜索患者</label>
                                <input type="text" class="form-control" id="search" name="search" placeholder="姓名或电话" value="<?php echo htmlspecialchars($search_filter); ?>">
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">筛选</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 预约列表 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">预约列表</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>ID</th>
                                        <th>患者姓名</th>
                                        <th>联系电话</th>
                                        <th>预约日期</th>
                                        <th>预约时间</th>
                                        <th>科室</th>
                                        <th>症状</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($appointments->num_rows > 0): ?>
                                        <?php while ($appointment = $appointments->fetch_assoc()): ?>
                                            <tr>
                                                <td><?php echo $appointment['id']; ?></td>
                                                <td><?php echo htmlspecialchars($appointment['patient_name']); ?></td>
                                                <td><?php echo htmlspecialchars($appointment['patient_phone']); ?></td>
                                                <td><?php echo htmlspecialchars($appointment['appointment_date']); ?></td>
                                                <td><?php echo htmlspecialchars($appointment['appointment_time']); ?></td>
                                                <td><?php echo htmlspecialchars($appointment['department_name']); ?></td>
                                                <td>
                                                    <?php 
                                                    $symptoms = htmlspecialchars($appointment['symptoms']);
                                                    echo strlen($symptoms) > 30 ? substr($symptoms, 0, 30) . '...' : $symptoms; 
                                                    ?>
                                                </td>
                                                <td>
                                                    <?php 
                                                    switch($appointment['status']) {
                                                        case 'pending':
                                                            echo '<span class="badge bg-warning">待确认</span>';
                                                            break;
                                                        case 'confirmed':
                                                            echo '<span class="badge bg-primary">已确认</span>';
                                                            break;
                                                        case 'completed':
                                                            echo '<span class="badge bg-success">已完成</span>';
                                                            break;
                                                        case 'cancelled':
                                                            echo '<span class="badge bg-danger">已取消</span>';
                                                            break;
                                                        default:
                                                            echo '<span class="badge bg-secondary">未知</span>';
                                                    }
                                                    ?>
                                                </td>
                                                <td>
                                                    <div class="btn-group">
                                                        <button type="button" class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#viewModal<?php echo $appointment['id']; ?>">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#statusModal<?php echo $appointment['id']; ?>">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <?php if ($appointment['status'] == 'confirmed' || $appointment['status'] == 'completed'): ?>
                                                            <a href="create_record.php?appointment_id=<?php echo $appointment['id']; ?>" class="btn btn-sm btn-success">
                                                                <i class="fas fa-notes-medical"></i>
                                                            </a>
                                                        <?php endif; ?>
                                                    </div>

                                                    <!-- 查看预约详情模态框 -->
                                                    <div class="modal fade" id="viewModal<?php echo $appointment['id']; ?>" tabindex="-1" aria-labelledby="viewModalLabel<?php echo $appointment['id']; ?>" aria-hidden="true">
                                                        <div class="modal-dialog modal-lg">
                                                            <div class="modal-content">
                                                                <div class="modal-header">
                                                                    <h5 class="modal-title" id="viewModalLabel<?php echo $appointment['id']; ?>">预约详情</h5>
                                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                </div>
                                                                <div class="modal-body">
                                                                    <div class="row">
                                                                        <div class="col-md-6">
                                                                            <h6>预约信息</h6>
                                                                            <p><strong>预约ID：</strong> <?php echo $appointment['id']; ?></p>
                                                                            <p><strong>预约日期：</strong> <?php echo htmlspecialchars($appointment['appointment_date']); ?></p>
                                                                            <p><strong>预约时间：</strong> <?php echo htmlspecialchars($appointment['appointment_time']); ?></p>
                                                                            <p><strong>预约状态：</strong> 
                                                                                <?php 
                                                                                switch($appointment['status']) {
                                                                                    case 'pending':
                                                                                        echo '<span class="badge bg-warning">待确认</span>';
                                                                                        break;
                                                                                    case 'confirmed':
                                                                                        echo '<span class="badge bg-primary">已确认</span>';
                                                                                        break;
                                                                                    case 'completed':
                                                                                        echo '<span class="badge bg-success">已完成</span>';
                                                                                        break;
                                                                                    case 'cancelled':
                                                                                        echo '<span class="badge bg-danger">已取消</span>';
                                                                                        break;
                                                                                    default:
                                                                                        echo '<span class="badge bg-secondary">未知</span>';
                                                                                }
                                                                                ?>
                                                                            </p>
                                                                            <p><strong>创建时间：</strong> <?php echo htmlspecialchars($appointment['created_at']); ?></p>
                                                                        </div>
                                                                        <div class="col-md-6">
                                                                            <h6>患者信息</h6>
                                                                            <p><strong>姓名：</strong> <?php echo htmlspecialchars($appointment['patient_name']); ?></p>
                                                                            <p><strong>联系电话：</strong> <?php echo htmlspecialchars($appointment['patient_phone']); ?></p>
                                                                            <p><strong>科室：</strong> <?php echo htmlspecialchars($appointment['department_name']); ?></p>
                                                                            <p><strong>医生：</strong> <?php echo htmlspecialchars($appointment['doctor_name']); ?></p>
                                                                        </div>
                                                                    </div>
                                                                    <hr>
                                                                    <div class="row">
                                                                        <div class="col-12">
                                                                            <h6>症状描述</h6>
                                                                            <p><?php echo nl2br(htmlspecialchars($appointment['symptoms'])); ?></p>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div class="modal-footer">
                                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                                                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#statusModal<?php echo $appointment['id']; ?>" data-bs-dismiss="modal">更新状态</button>
                                                                    <?php if ($appointment['status'] == 'confirmed' || $appointment['status'] == 'completed'): ?>
                                                                        <a href="create_record.php?appointment_id=<?php echo $appointment['id']; ?>" class="btn btn-success">创建病历</a>
                                                                    <?php endif; ?>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <!-- 更新状态模态框 -->
                                                    <div class="modal fade" id="statusModal<?php echo $appointment['id']; ?>" tabindex="-1" aria-labelledby="statusModalLabel<?php echo $appointment['id']; ?>" aria-hidden="true">
                                                        <div class="modal-dialog">
                                                            <div class="modal-content">
                                                                <div class="modal-header">
                                                                    <h5 class="modal-title" id="statusModalLabel<?php echo $appointment['id']; ?>">更新预约状态</h5>
                                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                </div>
                                                                <form action="" method="post">
                                                                    <div class="modal-body">
                                                                        <input type="hidden" name="appointment_id" value="<?php echo $appointment['id']; ?>">
                                                                        <input type="hidden" name="update_status" value="1">
                                                                        <div class="mb-3">
                                                                            <label for="status<?php echo $appointment['id']; ?>" class="form-label">选择状态</label>
                                                                            <select class="form-select" id="status<?php echo $appointment['id']; ?>" name="status" required>
                                                                                <option value="pending" <?php echo $appointment['status'] == 'pending' ? 'selected' : ''; ?>>待确认</option>
                                                                                <option value="confirmed" <?php echo $appointment['status'] == 'confirmed' ? 'selected' : ''; ?>>已确认</option>
                                                                                <option value="completed" <?php echo $appointment['status'] == 'completed' ? 'selected' : ''; ?>>已完成</option>
                                                                                <option value="cancelled" <?php echo $appointment['status'] == 'cancelled' ? 'selected' : ''; ?>>已取消</option>
                                                                            </select>
                                                                        </div>
                                                                    </div>
                                                                    <div class="modal-footer">
                                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                                                        <button type="submit" class="btn btn-primary">保存更改</button>
                                                                    </div>
                                                                </form>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="9" class="text-center">没有找到符合条件的预约记录</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 脚本 -->
    <script src="/assets\js/jquery-3.6.0.min.js"></script></script></script>
    <script src="/assets\js/bootstrap.bundle.min.js"></script></script></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="/assets\js/zh_c5ee11e1.js"></script></script></script></script>
    <script>
        // 初始化日期选择器
        document.addEventListener('DOMContentLoaded', function() {
            flatpickr(".datepicker", {
                locale: "zh",
                dateFormat: "Y-m-d",
                allowInput: true
            });
        });
    </script>
</body>
</html> 